package com.web.base.auth.provider;

import com.blue.jdbc.Page;
import com.blue.validation.ValidationUtil;
import com.blue.validation.group.SaveModel;
import com.blue.validation.group.UpdateModel;
import com.web.base.auth.cache.RoleUserCache;
import com.web.base.auth.exception.RoleException;
import com.web.base.auth.facade.RoleFacade;
import com.web.base.auth.message.RoleRequest;
import com.web.base.auth.message.RoleResponse;
import com.web.base.auth.message.RoleUserRequest;
import com.web.base.auth.model.Role;
import com.web.base.auth.service.RoleService;
import com.web.base.auth.util.RoleConvertor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component("authRoleProvider")
public class RoleProvider implements RoleFacade
{
	@Autowired
	private RoleService roleService;
	@Autowired
	private RoleUserCache roleUserCache;
	
	public RoleProvider()
	{
	}

	@Override
	public RoleResponse add(RoleRequest request)
	{
		ValidationUtil.valid(request, SaveModel.class);
		Role role = RoleConvertor.toRole(request);
		role = roleService.save(role);
		RoleResponse response = RoleConvertor.toResponse(role);
		return response;
	}

	@Override
	public RoleResponse update(RoleRequest request)
	{
		ValidationUtil.valid(request, UpdateModel.class);
		Role role = RoleConvertor.toRole(request);
		role = roleService.save(role);
		RoleResponse response = RoleConvertor.toResponse(role);
		return response;
	}

	@Override
	public RoleResponse get(Integer id)
	{
		if (id == null)
			throw new RoleException("角色ID不能为空");
		
		Role role = roleService.get(id);
		RoleResponse response = RoleConvertor.toResponse(role);
		return response;
	}

	@Override
	public Page<RoleResponse> listPage(RoleRequest request, int start, int size)
	{
		Role role = RoleConvertor.toRole(request);
		Page<Role> page = new Page<>(size);
		page.setCurPage(start);
		page = roleService.list(role, page);
		Page<RoleResponse> responsePage = RoleConvertor.toResponse(page);
		return responsePage;
	}

	@Override
	public void refresh()
	{
		roleUserCache.delete();
	}

	@Override
	public void addRoleUser(RoleUserRequest request)
	{
		ValidationUtil.valid(request, SaveModel.class);
		roleService.addRoleUser(request.getUserId(), request.getRoleIds());
		roleUserCache.delete();
	}

	@Override
	public List<RoleResponse> listSelect(Integer userId)
	{
		if (userId == null)
			throw new RoleException("用户ID不能为空");
		
		List<Role> list = roleService.listSelect(userId);
		List<RoleResponse> responseList = RoleConvertor.toResponse(list);
		return responseList;
	}
	
}
